package com.pengheng.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @remark
 * @Author pengheng
 * @date 2021/5/8 10:15
 */
@Slf4j
@Configuration
public class RabbitMQConfig {

    @Bean
    MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    @Autowired
    private RabbitTemplate rabbitTemplate;

    //构造器创建完成后调用
    @PostConstruct
    public void initRabbitTemplate() {
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            /**
             *
             * @param correlationData 当前消息的唯一关联数据（唯一id）
             * @param ack 消息是否成功收到
             * @param cause 失败原因
             */
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                log.info("cornfirm...correlationData[{}}]==>ack[{}}]====>cause[{}}]", correlationData, ack, cause);
            }
        });

        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            /**
             * 消息没有投递到指定的队列出发该回调方法
             * @param message 投递失败的信息
             * @param replyCode 回复的状态码
             * @param replyText 回复的文本内容
             * @param exchange 请求发送的交换机名称
             * @param routingKey 请求发送的路由键名称
             */
            @Override
            public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
                log.info("returnedMessage...message[{}}]==>replyCode[{}}]====>replyText[{}}]====>exchange[{}}]====>routingKey[{}}]", message, replyCode, replyText, exchange, routingKey);
            }
        });
    }
}
